<template>
  <div class="notification-bell">
    <el-dropdown
      trigger="click"
      placement="bottom-end"
      @command="handleCommand"
      class="notification-dropdown"
    >
      <div class="notification-trigger" @click="handleBellClick">
        <el-badge
          :value="notificationStore.unreadCount"
          :hidden="!notificationStore.hasUnreadNotifications"
          :max="99"
          class="notification-badge"
        >
          <el-button
            text
            circle
            size="large"
            class="notification-button"
          >
            <el-icon :size="20">
              <Bell />
            </el-icon>
          </el-button>
        </el-badge>
      </div>

      <template #dropdown>
        <el-dropdown-menu class="notification-menu">
          <!-- 头部 -->
          <div class="notification-header">
            <div class="header-title">
              <span>通知消息</span>
              <el-badge
                v-if="notificationStore.unreadCount > 0"
                :value="notificationStore.unreadCount"
                :max="99"
                type="danger"
              />
            </div>
            <div class="header-actions">
              <el-button
                v-if="notificationStore.unreadCount > 0"
                type="text"
                size="small"
                @click="markAllAsRead"
              >
                全部已读
              </el-button>
            </div>
          </div>

          <el-divider style="margin: 8px 0;" />

          <!-- 通知列表 -->
          <div class="notification-list">
            <template v-if="notificationStore.unreadNotifications.length > 0">
              <div
                v-for="notification in displayNotifications"
                :key="notification.id"
                class="notification-item"
                :class="{ 'unread': notification.status === 'UNREAD' }"
                @click="handleNotificationClick(notification)"
              >
                <div class="notification-icon">
                  <el-icon
                    :color="getIconColor(notification.type)"
                    :size="16"
                  >
                    <component :is="getIconComponent(notification.type)" />
                  </el-icon>
                </div>
                <div class="notification-content">
                  <div class="notification-title">{{ notification.title }}</div>
                  <div class="notification-text">{{ notification.content }}</div>
                  <div class="notification-time">{{ formatTime(notification.createdAt) }}</div>
                </div>
                <div v-if="notification.status === 'UNREAD'" class="unread-dot"></div>
              </div>
            </template>
            
            <div v-else class="no-notifications">
              <el-icon :size="40" color="#c0c4cc">
                <Bell />
              </el-icon>
              <p>暂无新通知</p>
            </div>
          </div>

          <el-divider style="margin: 8px 0;" />

          <!-- 底部操作 -->
          <div class="notification-footer">
            <el-dropdown-item command="viewAll" class="footer-link">
              查看全部通知
            </el-dropdown-item>
          </div>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Bell, 
  SuccessFilled,
  WarningFilled, 
  InfoFilled,
  CircleCloseFilled
} from '@element-plus/icons-vue'
import { useNotificationStore } from '../stores/notification'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

const router = useRouter()
const notificationStore = useNotificationStore()

// 显示的通知列表（最多显示5条）
const displayNotifications = computed(() => {
  return notificationStore.unreadNotifications.slice(0, 5)
})

// 处理铃铛点击
const handleBellClick = async () => {
  // 刷新通知统计
  await notificationStore.fetchNotificationStats()
  
  // 如果有未读通知，获取详细列表
  if (notificationStore.unreadCount > 0) {
    await notificationStore.fetchUnreadNotifications()
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'viewAll':
      router.push('/notifications')
      break
  }
}

// 处理通知点击
const handleNotificationClick = async (notification) => {
  // 标记为已读
  if (notification.status === 'UNREAD') {
    await notificationStore.markNotificationAsRead(notification.id)
  }
  
  // 根据通知类型导航到相应页面
  switch (notification.type) {
    case 'AVATAR_APPROVED':
    case 'AVATAR_REJECTED':
      router.push('/profile?tab=avatar')
      break
    default:
      // 其他类型通知可以导航到通知详情页面
      router.push('/notifications')
  }
}

// 标记所有通知为已读
const markAllAsRead = async () => {
  await notificationStore.markAllNotificationsAsRead()
}

// 获取图标组件
const getIconComponent = (type) => {
  const iconMap = {
    'AVATAR_APPROVED': SuccessFilled,
    'AVATAR_REJECTED': WarningFilled,
    'SYSTEM_NOTICE': InfoFilled,
    'SECURITY_ALERT': CircleCloseFilled
  }
  return iconMap[type] || InfoFilled
}

// 获取图标颜色
const getIconColor = (type) => {
  const colorMap = {
    'AVATAR_APPROVED': '#67C23A',
    'AVATAR_REJECTED': '#E6A23C',
    'SYSTEM_NOTICE': '#409EFF',
    'SECURITY_ALERT': '#F56C6C'
  }
  return colorMap[type] || '#409EFF'
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  try {
    const date = new Date(timeString)
    return formatDistanceToNow(date, { 
      addSuffix: true, 
      locale: zhCN 
    })
  } catch (error) {
    return timeString
  }
}

// 定时检查新通知
let notificationTimer = null

const startNotificationTimer = () => {
  // 每30秒检查一次新通知
  notificationTimer = setInterval(() => {
    notificationStore.checkForNewNotifications()
  }, 30000)
}

const stopNotificationTimer = () => {
  if (notificationTimer) {
    clearInterval(notificationTimer)
    notificationTimer = null
  }
}

// 组件挂载和卸载
onMounted(() => {
  console.log('🔔 NotificationBell组件已挂载')
  console.log('🔔 当前notificationStore:', notificationStore)
  console.log('🔔 开始获取通知统计...')
  
  // 初始加载通知统计
  notificationStore.fetchNotificationStats().then(result => {
    console.log('🔔 通知统计获取结果:', result)
  }).catch(error => {
    console.error('🔔 通知统计获取失败:', error)
  })
  
  // 开始定时检查
  startNotificationTimer()
  console.log('🔔 定时器已启动')
})

onUnmounted(() => {
  stopNotificationTimer()
})
</script>

<style scoped>
.notification-bell {
  position: relative;
}

.notification-trigger {
  cursor: pointer;
  display: inline-block;
}

.notification-badge {
  cursor: pointer;
}

.notification-button {
  color: white !important;
  transition: color 0.3s;
  pointer-events: none; /* 防止按钮本身的点击事件 */
}

.notification-trigger:hover .notification-button {
  color: var(--el-color-primary) !important;
  background-color: var(--el-color-primary-light-9);
}

.notification-menu {
  width: 350px;
  max-height: 500px;
  overflow: hidden;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px 0;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.header-actions {
  font-size: 12px;
}

.notification-list {
  max-height: 300px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
  border-radius: 4px;
  margin: 0 8px;
}

.notification-item:hover {
  background-color: var(--el-color-primary-light-9);
}

.notification-item.unread {
  background-color: var(--el-color-info-light-9);
}

.notification-icon {
  flex-shrink: 0;
  margin-top: 2px;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-size: 13px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
  line-height: 1.4;
}

.notification-text {
  font-size: 12px;
  color: var(--el-text-color-regular);
  line-height: 1.4;
  word-break: break-word;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 4px;
}

.notification-time {
  font-size: 11px;
  color: var(--el-text-color-placeholder);
}

.unread-dot {
  width: 6px;
  height: 6px;
  background-color: var(--el-color-danger);
  border-radius: 50%;
  flex-shrink: 0;
  margin-top: 8px;
}

.no-notifications {
  text-align: center;
  padding: 40px 20px;
  color: var(--el-text-color-placeholder);
}

.no-notifications p {
  margin: 12px 0 0;
  font-size: 14px;
}

.notification-footer {
  padding: 8px 0;
}

.footer-link {
  text-align: center;
  color: var(--el-color-primary);
  font-size: 13px;
}

/* 滚动条样式 */
.notification-list::-webkit-scrollbar {
  width: 4px;
}

.notification-list::-webkit-scrollbar-track {
  background: transparent;
}

.notification-list::-webkit-scrollbar-thumb {
  background: var(--el-border-color);
  border-radius: 2px;
}

.notification-list::-webkit-scrollbar-thumb:hover {
  background: var(--el-border-color-darker);
}
</style>
